<?php

namespace App\Http\Middleware;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AfterConvertResponseToCamelCase
{
    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);

        if ($response instanceof JsonResponse) {
            $response->setData($this->convert(json_decode($response->content(), true)));
        }

        return $response;
    }

    protected function convert($data) {
        if (!is_array($data)) return $data;

        $result= [];

        foreach ($data as $k=> $value) {
            $result[\Str::camel($k)] = is_array($value) ? $this->convert($value) : $value;
        }

        return $result;
    }
}
